<template>
  <div class="insert-container">
    <!-- 搜索 -->
    <div class="search-content">
      <a-input-search
        ref="searchInputRef"
        class="search-input"
        v-model.lazy="searchValue"
        placeholder="搜索您需要@的人"
        @compositionstart="cancelSearch"
        @compositionend="searchInput"
        @input="searchInput"
        @search="handleSearch"
      />
    </div>
    <div class="group-content">
      <a-checkbox-group
        class="checkbox-group-content"
        v-model="selectedAtId"
        direction="vertical"
        :max="9"
        @change="updateSelectedContacts"
        v-if="groupList && groupList.length > 0"
      >
        <template v-for="item in groupList" :key="item.webUserId">
          <a-checkbox :value="item.webUserId">
            <template #checkbox="{ checked }">
              <a-space
                align="start"
                class="custom-checkbox-card"
                :class="{ 'custom-checkbox-card-checked': checked }"
              >
                <!-- 多选框 -->
                <div className="custom-checkbox-card-mask">
                  <icon-check class="icon-check" />
                </div>
                <!-- 内容列表 -->
                <div class="custom-checkbox-content">
                  <a-avatar shape="square" :size="50">
                    <img alt="avatar" :src="getAvatar(item)" />
                  </a-avatar>
                  <div class="custom-checkbox-content-name">
                    <div class="name">{{ item.nickname }}</div>
                    <div class="introduction">{{ item.introduction }}</div>
                  </div>
                </div>
              </a-space>
            </template>
          </a-checkbox>
        </template>
      </a-checkbox-group>

      <div class="no-data" v-else>
        <template v-if="searchValue"> 无符合条件的用户 </template>
        <template v-else>暂无联系人</template>
      </div>
    </div>
    <!--已选择的成员-->
    <div
      class="selected-contacts"
      v-if="selectedContactsBackup && selectedContactsBackup.length > 0"
    >
      <div class="selected-contacts-content">
        <template v-for="item in selectedContactsBackup" :key="item.webUserId">
          <div class="selected-contacts-item">
            <a-avatar shape="square" :size="40">
              <img alt="avatar" :src="getAvatar(item)" />
            </a-avatar>
          </div>
        </template>
      </div>
      <div class="selected-contacts-title">
        已选({{ selectedContactsBackup.length }}/9)
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { getUserInfo } from "@/utils/auth";
import { getAllAppUser, getFollowersList } from "@/api/articleWorkBench";
import { getAvatar } from "@/utils/getAvatar";

const userInfo: any = getUserInfo();

const groupList = ref<any>([]);
const selectedAtId = ref<any>([]);
const selectedContactsBackup = ref<any>([]);
const allContactsBackup = ref<any>([]);

// 更新已选中的联系人
const updateSelectedContacts = (value: any[], target: any) => {
  let targetIdValue = target.currentTarget.value;
  //  已选人
  let nowPeople = JSON.parse(JSON.stringify(selectedContactsBackup.value));
  let _findIndex = nowPeople.findIndex((select: any) => {
    return select.webUserId == targetIdValue;
  });
  let selectItem = groupList.value.filter(
    (item: any) => targetIdValue == item.webUserId
  )[0];
  if (_findIndex > -1) {
    nowPeople.splice(_findIndex, 1);
  } else {
    nowPeople.push(selectItem);
  }
  selectedContactsBackup.value = nowPeople;
  selectedAtId.value = nowPeople.map((item: any) => {
    return item.webUserId;
  });
};

const removeFromSelectedContacts = (webUserId: string) => {
  selectedContactsBackup.value = selectedContactsBackup.value.filter(
    (contact: any) => contact.webUserId !== webUserId
  );
  selectedAtId.value = selectedContactsBackup.value.map(
    (contact: any) => contact.webUserId
  );
};

const getContactAtList = async () => {
  try {
    const userId = userInfo.id;
    const { data } = await getFollowersList(userId);
    groupList.value = data;
    allContactsBackup.value = data;
    restoreSelectedContacts();
  } catch (error) {
    console.log("获取用户失败：", error);
  }
};

const restoreSelectedContacts = () => {
  const selectedIds = selectedContactsBackup.value.map(
    (contact: any) => contact.webUserId
  );
  selectedAtId.value = selectedIds;
};

onMounted(() => {
  getContactAtList();
});

// 搜索
const searchValue = ref("");
let searchTimeout: any = null;

const searchInputRef = ref<any>();
const cancelSearch = () => {
  clearTimeout(searchTimeout);
};

const searchInput = () => {
  cancelSearch();
  searchTimeout = setTimeout(() => {
    handleSearch();
  }, 1000);
};

// 搜索处理
const handleSearch = async () => {
  if (searchValue.value) {
    const { data } = await getAllAppUser(searchValue.value);
    const searchResults = data;

    groupList.value = searchResults;
  } else {
    // 没有搜索值时恢复所有联系人
    groupList.value = allContactsBackup.value;
  }
};

const getSelectedAts = () => {
  return selectedContactsBackup.value;
};

defineExpose({
  getSelectedAts,
  removeFromSelectedContacts,
});
</script>
<style lang="less" scoped>
.insert-container {
  width: 100%;
  .search-content {
    width: 100%;
    height: 40px;
    margin: 0 auto;
    background-color: #f3f4f7;
    .arco-input-wrapper {
      height: 40px;
      line-height: 40px;
      font-weight: 400;
      font-size: 18px;
      color: #999ca1;
      background-color: transparent;
      &.arco-input-focus {
        background-color: transparent;
      }
    }
  }
  .group-content {
    width: 100%;
    height: 400px;
    overflow-y: auto;
  }
}
.custom-checkbox-card {
  padding: 10px 16px;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.custom-checkbox-card-mask {
  height: 21px;
  width: 21px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  border: 1px solid var(--color-border-2);
  box-sizing: border-box;
  background-color: white;
  .icon-check {
    display: none;
  }
}

// 选中的样式
.custom-checkbox-card-checked {
  .custom-checkbox-card-mask {
    border-color: rgb(var(--primary-6));
    background-color: rgb(var(--primary-6));
    .icon-check {
      display: inline-block;
      color: white;
      font-size: 16px;
    }
  }
}

.custom-checkbox-card-title {
  color: var(--color-text-1);
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
}

.custom-checkbox-card:hover,
.custom-checkbox-card-checked,
.custom-checkbox-card:hover .custom-checkbox-card-mask,
.custom-checkbox-card-checked .custom-checkbox-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-checkbox-card:hover .custom-checkbox-card-title,
.custom-checkbox-card-checked .custom-checkbox-card-title {
  color: rgb(var(--primary-6));
}

.custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
  background-color: rgb(var(--primary-6));
}

.custom-checkbox-content {
  display: flex;
  width: 100%;
  flex-direction: row;
  align-items: center;
  height: 50px;
  margin-left: 10px;
  .custom-checkbox-content-name {
    margin-left: 15px;
    width: 300px;
    height: 100%;

    .name {
      display: inline-block;
      height: 24px;
      width: 100%;
      // overflow: hidden;
      // text-overflow: ellipsis;
      // white-space: nowrap;
      font-weight: 400;
      font-size: 18px;
      color: #0a1220;
      line-height: 20px;
    }
    .introduction {
      height: 24px;
      display: block;
      width: 100%;
      // overflow: hidden;
      // text-overflow: ellipsis;
      // white-space: nowrap;
      font-weight: 400;
      font-size: 16px;
      color: #999ca1;
      line-height: 24px;
    }
  }
}

.selected-contacts {
  width: 100%;
  height: auto;
  background-color: #f3f4f7;
  border-radius: 8px;
  padding: 8px;
  display: flex;
  flex-direction: row;
  align-items: center;
  .selected-contacts-content {
    flex: 1;
    overflow-x: auto;
    display: flex;
    flex-direction: row;
    align-items: center;
    .selected-contacts-item {
      margin-right: 8px;
    }
  }
  .selected-contacts-title {
    font-weight: 400;
    font-size: 18px;
    color: #02d772;
    line-height: 32px;
  }
}
</style>
